package avater.appscomm.mydemo;

import android.Manifest;
import android.app.AlertDialog;
import android.content.ContentUris;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import java.io.File;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    public static final String AUTHOR_PROVIDERS = "com.appscomm.avater.fileprovider";

    private ImageView imageview;
    private Button pick;
    private Button start_carmer;
    /**
     * 选择图库,并选择具体图片后的返回值
     */
    private static final int REQUEST_PICK_IMAGE = 2;
    /**
     * 被选择图片的URI
     */
    private Uri imageUri;
    /**
     * 被选择图片的地址
     */
    private String imagePath;
    /**
     * 保存的URI
     */
    private Uri outputUri;
    /**
     * 裁剪图后
     */
    private static final int REQUEST_PICK_CUT = 3;
    private static final int REQUEST_CAPTURE = 7;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        pick = (Button) findViewById(R.id.pick);
        imageview = (ImageView) findViewById(R.id.imageview);
        start_carmer = (Button) findViewById(R.id.start_carmer);
        pick.setOnClickListener(this);
        start_carmer.setOnClickListener(this);
        /**
         * 必须授权，否则在选择图片裁剪后不能进行写入到SD卡的操作，会导致设置图片失败
         */
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 5);
        }
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 6);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.pick:
                if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA}, 1);
                } else {
                    Intent intent = new Intent(Intent.ACTION_PICK);
                    intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                    startActivityForResult(intent, REQUEST_PICK_IMAGE);
                }
                break;
            case R.id.start_carmer:
                if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA}, 1);
                } else {
                    openCamera();
                }
                break;
        }
    }

    /**
     * 打开相机
     */
    private void openCamera() {
        File file = new FileStorage().createCropFile();
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
            try {
                imageUri = FileProvider.getUriForFile(MainActivity.this, AUTHOR_PROVIDERS, file);
            } catch (Exception e) {
                e.printStackTrace();
                imageUri = Uri.fromFile(file);
            }
        } else
            imageUri = Uri.fromFile(file);
        Intent intent = new Intent();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent, REQUEST_CAPTURE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_PICK_IMAGE) {
            if (resultCode == RESULT_CANCELED) {
                return;//没有选择图片
            }
            if (Build.VERSION.SDK_INT >= 19) {//机型适配
                handleImageOnKitKat(data);//7.0
            } else {
                handleImageBeforeKitKat(data);
            }
        }
        if (requestCode == REQUEST_PICK_CUT) {//裁剪后
            Bitmap bitmap = null;
            try {
                bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(outputUri));
                imageview.setImageBitmap(bitmap);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (requestCode == REQUEST_CAPTURE) {//拍照返回
            if (resultCode == RESULT_OK) {
                cropPhoto();
            }
        }
    }

    /**
     * 获取文件路径
     *
     * @param data
     */
    private void handleImageBeforeKitKat(Intent data) {
        imageUri = data.getData();
        imagePath = getImagePath(imageUri, null);
        cropPhoto();
    }

    /**
     * 裁剪图片
     */
    private void cropPhoto() {
        File file = new FileStorage().createCropFile();
        outputUri = Uri.fromFile(file);
        Intent intent = new Intent("com.android.camera.action.CROP");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        intent.setDataAndType(imageUri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("scale", true);
        intent.putExtra("return-data", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        intent.putExtra("outputX", 96);//指定裁剪后图片的大小，避免出现大图片上传失败的情况
        intent.putExtra("outputY", 96);//
        startActivityForResult(intent, REQUEST_PICK_CUT);
    }

    /**
     * 获取各个版本的文件的路径
     *
     * @param data
     */
    private void handleImageOnKitKat(Intent data) {
        imagePath = null;
        imageUri = data.getData();
        if (DocumentsContract.isDocumentUri(this, imageUri)) {
            String docId = DocumentsContract.getDocumentId(imageUri);
            if ("com.android.providers.media.documents".equals(imageUri.getAuthority())) {
                String id = docId.split(":")[1];
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.downloads.documents".equals(imageUri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(imageUri.getScheme())) {
            imagePath = getImagePath(imageUri, null);
        } else if ("file".equalsIgnoreCase(imageUri.getScheme())) {
            imagePath = imageUri.getPath();
        }
        cropPhoto();
    }

    /**
     * 获取文件路径
     *
     * @param uri
     * @param selection
     * @return
     */
    private String getImagePath(Uri uri, String selection) {
        String path = null;
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }
}
